package br.com.amadeus.android.dao;


import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import br.com.amadeus.android.entities.Action;
import br.com.amadeus.android.entities.Resource;

public class ActionDAO {
	public static String[] columns = new String[] { ActionDAO.ID,
			ActionDAO.VALUE };

	public static final String ID = "_id";
	public static final String VALUE = "value";

	private SQLiteDatabase db;

	private static ActionDAO instance = new ActionDAO();

	public static ActionDAO getInstance(Context ctx) {

		if (instance.db == null || !instance.db.isOpen()) {
			instance.db = new DBHelper(ctx).getWritableDatabase();
		}
		return instance;
	}

	private ActionDAO() {
	}

	public long save(Action action) {
		long id = action.getId();
		if (id == 0) {
			return insert(action);
		} else {
			return update(action);
		}
	}

	private long insert(Action action) {
		long id_action = -1;

		db.beginTransaction();
		try {

			ContentValues values = new ContentValues();
			values.put(ActionDAO.VALUE, action.getValue());

			id_action = db.insert(DBHelper.TABLE_ACTION, null, values);
			
			if (id_action != -1)
				db.setTransactionSuccessful();

		} finally {
			db.endTransaction();
		}

		return id_action;
	}

	private long update(Action action) {
		boolean deuErro = false;
		db.beginTransaction();
		try {
			ContentValues values = new ContentValues();
			values.put(ActionDAO.VALUE, action.getValue());

			deuErro = db.update(DBHelper.TABLE_ACTION, values, ActionDAO.ID
					+ " = ?", new String[] { String.valueOf(action.getId()) }) == 0;

			if (!deuErro)
				db.setTransactionSuccessful();

		} finally {
			db.endTransaction();
		}
		return action.getId();
	}
	
	public void delete(int id) {
		db.beginTransaction();
		try {
			db.delete(DBHelper.TABLE_ACTION, ActionDAO.ID + "=?",
					new String[] { String.valueOf(id) });
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}
	
	public Action getAction(int id){
		Action action = null;
		Cursor c = db.query(DBHelper.TABLE_ACTION, null, ActionDAO.ID + "=" + id,
				null, null, null, null);
		if (c.getCount() > 0) {
			c.moveToFirst();
			action = fillAction(c);
		}
		c.close();
		return action;
	}
	
	protected static Action fillAction(Cursor c){
		int id = c.getInt(c.getColumnIndex(ActionDAO.ID));
		String value = c.getString(c.getColumnIndex(ActionDAO.VALUE));
		return new Action(id, value);
	}

	public ArrayList<Action> getAllActions() {
		ArrayList<Action> listActions = new ArrayList<Action>();
		Cursor c = db.query(DBHelper.TABLE_ACTION, null, null,
				null, null, null, null);
		if (c.getCount() > 0) {
			c.moveToFirst();
			do{
				listActions.add(fillAction(c));
			}while(c.moveToNext()); 
		}
		c.close();
		return listActions; 
	}
}
